package com.xxwu.propertieskaptcha;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
@RestController
@RequestMapping("/KaptchaController")
public class KaptchaController {
    private final static String KAPTCHA_SESSION_KEY = "KAPTCHA_SESSION_KEY";
    private final static String KAPTCHA_SESSION_DATE = "KAPTCHA_SESSION_DATE";
    private final static int DATA = 60 * 1000;
    @RequestMapping("/check")
    public boolean check(String input, HttpSession session) {
        //检查用户输入是否为空
        if(!StringUtils.hasLength(input)) {
            return false;
        }
        //获取当前验证码，时间
        String currentSession = (String) session.getAttribute(KAPTCHA_SESSION_KEY);
        Date currentDate = (Date) session.getAttribute(KAPTCHA_SESSION_DATE);
        //比对验证码是否正确
        if(input.equals(currentSession)) {
            //检查验证码是否超时
            if(System.currentTimeMillis() - currentDate.getTime() < DATA) {
                return true;
            }
        }
        return false;
    }
}
